import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Title: loginServlet
 * @Author 郑雨杭
 * @Package PACKAGE_NAME
 * @Date 2024/7/27 21:28
 * @description:
 */
@WebServlet("/login")
public class loginServlet extends HttpServlet {
    DataSource dataSource = new MysqlDataSource();

    @Override
    public void init() throws ServletException {
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/users?useSSL=false&characterEncoding=utf8");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
            Connection connection = dataSource.getConnection();
            String sql = "select * from users where username = ? and password = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            ResultSet resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                System.out.println("密码正确");
                //resp.sendRedirect(req.getContextPath()+"/hello.html");
                //req.getRequestDispatcher("/hello").forward(req,resp);
                HttpSession session = req.getSession(true);
                session.setAttribute("username",username);
                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                session.setAttribute("loginTime",dateFormat.format(date));
                Cookie cookie = new Cookie("JSESSIONID",session.getId());
                cookie.setMaxAge(60*5);
                resp.addCookie(cookie);
                resp.sendRedirect(req.getContextPath()+"/hello");
            }else{
                System.out.println("密码错误");
                resp.sendRedirect(req.getContextPath()+"/login.html");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
